package com.zrrd.jt_admin.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.jt_admin.common.vo.RoleVo;
import com.zrrd.jt_admin.common.bo.RoleRuleBo;
import com.zrrd.jt_admin.common.entity.Role;
import com.zrrd.jt_admin.common.entity.RoleRule;
import com.zrrd.jt_admin.common.vo.RolePageVo;
import com.zrrd.jt_admin.manager.mapper.RoleMapper;
import com.zrrd.jt_admin.manager.service.RoleRuleService;
import com.zrrd.jt_admin.manager.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zhangyk
 * @since 2024-06-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleRuleService roleRuleService;



    /**
     * 根据role_id获取rules权限列表
     * @param id
     * @return
     */
    private List<RoleRuleBo> getRoleRuleBoList(Integer id) {
        List<RoleRule> roleRuleList = roleRuleService.lambdaQuery().eq(RoleRule::getRoleId, id).list();
        List<RoleRuleBo> roleRuleBos = roleRuleList.stream().map(roleRule -> {
            RoleRuleBo roleRuleBo = new RoleRuleBo();
            roleRuleBo.setId(roleRule.getRuleId());
            roleRuleBo.setPivot(roleRule);
            return roleRuleBo;
        }).collect(Collectors.toList());
        return roleRuleBos;
    }

    @Override
    public RolePageVo findByPage(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        //查询所有role
        List<Role> roleList = list();
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        RolePageVo rolePageVo = new RolePageVo();
        rolePageVo.setTotalCount(pageInfo.getTotal());

        List<RoleVo> roleVos = new ArrayList<>();
        roleVos = roleList.stream().map(role -> {
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(role, roleVo);
            List<RoleRuleBo> rules = getRoleRuleBoList(role.getId());
            roleVo.setRules(rules);
            return roleVo;
        }).collect(Collectors.toList());

        rolePageVo.setRoleVos(roleVos);

        return rolePageVo;
    }

    @Override
    public RoleVo findById(Integer id) {
        Role role = getById(id);
        RoleVo roleVo = new RoleVo();
        BeanUtils.copyProperties(role, roleVo);
        List<RoleRuleBo> rules = getRoleRuleBoList(id);
        roleVo.setRules(rules);
        return roleVo;
    }
}
